﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myBoard.App.MagnetStore;
using System.ComponentModel;

namespace myBoard.App.Components.MagnetsStore
{
    public static class MagnetsStoreClient
    {
        static MagnetsStoreSoapClient _client;
        static bool _storeClientInitialized;
        public delegate void StoreClientInitilizedHandler(MagnetsStoreSoapClient client);
        public static event StoreClientInitilizedHandler StoreClientInitilized;

        public static MagnetsStoreSoapClient Client
        {
            get 
            {
                if (!_storeClientInitialized)
                    throw new Exception("Magnet Store client not initialized");

                return _client; 
            }
        }

        public static void InitilizeMagnetStoreClient()
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (sender, e) =>
                {
                    MagnetsStoreSoapClient client = new MagnetsStoreSoapClient();
                    
                    e.Result = client;
                };
            bw.RunWorkerCompleted += (sender, e) =>
                {
                    if (e.Error != null)
                        throw new Exception("Cannot connect to Magnet Store", e.Error);

                    _client = e.Result as MagnetsStoreSoapClient;
                    _storeClientInitialized = true;
                    if (StoreClientInitilized != null)
                        StoreClientInitilized(_client);
                };
            bw.RunWorkerAsync();
        }
    }
}
